#!/bin/bash

# 驱动模块定义
# DRIVER_DIR="/lib/modules/5.10.209-rt89+/kernel/drivers/char/"
DRIVER_DIR="/lib/modules/4.19.232-rt104+/kernel/drivers/char/"
DRIVER_FILE=pcie_mcdev.ko
DRIVER_INIT_DIR="/etc/init.d/"
DRIVER_INIT_FILE=S99mcdev_driver

# 库定义
LIB_DIR="/usr/lib/"
LIB_NAME=libpcie_mcdev
STATIC_LIB=libpcie_mcdev.a
DYNAMIC_LIB_REALNAME=libpcie_mcdev.so.1.0.0
DYNAMIC_LIB_SONAME=libpcie_mcdev.so.1
DYNAMIC_LIB_LINKNAME=libpcie_mcdev.so

# 测试程序
TEST_DIR="/usr/bin/"
TEST_FILE=unit_test_v1

# 打印配置
DEBUG=true
COLOR_RED='\033[0;31m'
COLOR_GREEN='\033[0;32m'
COLOR_YELLOW='\033[1;33m'
COLOR_RESET='\033[0m'
prt_info() {
    echo -e "${COLOR_GREEN}$1${COLOR_RESET}"
}
prt_warn() {
    echo -e "${COLOR_YELLOW}$1${COLOR_RESET}"
}
prt_erro() {
    echo -e "${COLOR_RED}$1${COLOR_RESET}"
}
prt_dbug() {
    # 只在调试模式下输出
    if [ "$DEBUG" = "true" ]; then
        echo -e "${COLOR_RESET}$1${COLOR_RESET}" >&2
    fi
}

# 检查权限
check_permission() {
    if [ "$EUID" -eq 0 ] && [ -n "$SUDO_USER" ]; then
        prt_dbug "脚本通过 sudo 并以 root 权限运行"
    elif [ "$EUID" -eq 0 ]; then
        prt_dbug "脚本以 root 权限运行，但不是通过 sudo"
    else
        prt_erro "请通过 sudo 或以 root 权限运行"
        exit 1
    fi
}

# 检查文件是否存在
check_file_exists() {
    local file="$1"
    if [ -f "$file" ]; then
        return 0
    else
        return 1
    fi
}

# 安装函数
install_libraries() {
    prt_info "开始安装驱动文件..."
    # 检查驱动目录是否存在
    if [ ! -d "$DRIVER_DIR" ]; then
        prt_erro "驱动目录不存在: $DRIVER_DIR"
        mkdir -p $DRIVER_DIR
    fi
    # 检查驱动文件是否存在
    if ! check_file_exists "$DRIVER_FILE"; then
        prt_erro "驱动文件不存在: $DRIVER_FILE"
        exit 1
    fi
    # 安装驱动
    prt_info "安装驱动: $DRIVER_FILE -> $DRIVER_DIR"
    cp "$DRIVER_FILE" "$DRIVER_DIR" && chmod 644 "$DRIVER_DIR/$DRIVER_FILE"
    if [ $? -eq 0 ]; then
        prt_dbug "驱动安装成功"
    else
        prt_erro "驱动安装失败"
        exit 1
    fi
    # 加载脚本目录是否存在
    if [ ! -d "$DRIVER_INIT_DIR" ]; then
        prt_erro "加载脚本目录不存在: $DRIVER_INIT_DIR"
        mkdir -p $DRIVER_INIT_DIR
    fi
    # 检查库文件是否存在
    if ! check_file_exists "$DRIVER_INIT_FILE"; then
        prt_erro "加载脚本文件不存在: $DRIVER_INIT_FILE"
        exit 1
    fi
    # 安装驱动
    prt_info "安装加载脚本: $DRIVER_INIT_FILE -> $DRIVER_INIT_DIR"
    cp "$DRIVER_INIT_FILE" "$DRIVER_INIT_DIR" && chmod 755 "$DRIVER_INIT_DIR/$DRIVER_INIT_FILE"
    if [ $? -eq 0 ]; then
        prt_dbug "加载脚本安装成功"
    else
        prt_erro "加载脚本安装失败"
        exit 1
    fi

    prt_info "开始安装库文件..."
    # 检查目标目录是否存在
    if [ ! -d "$LIB_DIR" ]; then
        prt_erro "目标目录不存在: $LIB_DIR"
        exit 1
    fi
    # 检查库文件是否存在
    if ! check_file_exists "$STATIC_LIB"; then
        prt_erro "静态库文件不存在: $STATIC_LIB"
        exit 1
    fi
    if ! check_file_exists "$DYNAMIC_LIB_REALNAME"; then
        prt_erro "动态库文件不存在: $DYNAMIC_LIB_REALNAME"
        exit 1
    fi
    # 安装静态库
    prt_info "安装静态库: $STATIC_LIB -> $LIB_DIR"
    cp "$STATIC_LIB" "$LIB_DIR" && chmod 644 "$LIB_DIR/$STATIC_LIB"
    if [ $? -eq 0 ]; then
        prt_dbug "静态库安装成功"
    else
        prt_erro "静态库安装失败"
        exit 1
    fi
    # 安装动态库
    prt_info "安装动态库: $DYNAMIC_LIB_REALNAME -> $LIB_DIR"
    cp "$DYNAMIC_LIB_REALNAME" "$LIB_DIR" && chmod 755 "$LIB_DIR/$DYNAMIC_LIB_REALNAME"
    if [ $? -eq 0 ]; then
        prt_dbug "动态库安装成功"
    else
        prt_erro "动态库安装失败"
        exit 1
    fi
    # 创建符号链接
    pushd "$LIB_DIR"
    # 创建 SONAME 链接
    if [ -f "$DYNAMIC_LIB_REALNAME" ]; then
        prt_info "创建符号链接: $DYNAMIC_LIB_SONAME -> $DYNAMIC_LIB_REALNAME"
        ln -sf "$DYNAMIC_LIB_REALNAME" "$DYNAMIC_LIB_SONAME"
        # 创建主链接
        prt_info "创建符号链接: $DYNAMIC_LIB_LINKNAME -> $DYNAMIC_LIB_SONAME"
        ln -sf "$DYNAMIC_LIB_SONAME" "$DYNAMIC_LIB_LINKNAME"
        prt_dbug "符号链接创建成功"
    fi
    # 更新动态库缓存
    prt_info "更新动态库缓存..."
    ldconfig
    prt_dbug "所有库文件安装完成"
    # 显示安装结果
    echo
    prt_info "安装的文件列表:"
    ls -la "$LIB_DIR" | grep $LIB_NAME
    popd

    prt_info "开始安装测试程序文件..."
    # 检查测试程序目录是否存在
    if [ ! -d "$TEST_DIR" ]; then
        prt_erro "测试程序目录不存在: $TEST_DIR"
        mkdir -p $TEST_DIR
    fi
    # 检查测试程序文件是否存在
    if ! check_file_exists "$TEST_FILE"; then
        prt_erro "测试程序文件不存在: $TEST_FILE"
        exit 1
    fi
    # 安装测试程序
    prt_info "安装测试程序: $TEST_FILE -> $TEST_DIR"
    cp "$TEST_FILE" "$TEST_DIR" && chmod 755 "$TEST_DIR/$TEST_FILE"
    if [ $? -eq 0 ]; then
        prt_dbug "测试程序安装成功"
    else
        prt_erro "测试程序安装失败"
        exit 1
    fi
}

# 卸载函数
uninstall_libraries() {
    prt_info "开始卸载驱动文件..."
    # 检查文件是否存在并删除
    local files_removed=0
    # 删除驱动
    if check_file_exists "$DRIVER_DIR/$DRIVER_FILE"; then
        prt_info "删除驱动: $DRIVER_DIR/$DRIVER_FILE"
        rm -f "$DRIVER_DIR/$DRIVER_FILE"
        files_removed=$((files_removed + 1))
    else
        prt_warn "驱动不存在: $DRIVER_DIR/$DRIVER_FILE"
    fi
    # 删除加载脚本
    if check_file_exists "$DRIVER_INIT_DIR/$DRIVER_INIT_FILE"; then
        prt_info "删除加载脚本: $DRIVER_INIT_DIR/$DRIVER_INIT_FILE"
        rm -f "$DRIVER_INIT_DIR/$DRIVER_INIT_FILE"
        files_removed=$((files_removed + 1))
    else
        prt_warn "加载脚本不存在: $DRIVER_INIT_DIR/$DRIVER_INIT_FILE"
    fi

    prt_info "开始卸载库文件..."
    # 检查文件是否存在并删除
    # local files_removed=0
    # 删除静态库
    if check_file_exists "$LIB_DIR/$STATIC_LIB"; then
        prt_info "删除静态库: $LIB_DIR/$STATIC_LIB"
        rm -f "$LIB_DIR/$STATIC_LIB"
        files_removed=$((files_removed + 1))
    else
        prt_warn "静态库不存在: $LIB_DIR/$STATIC_LIB"
    fi
    # 删除动态库文件
    if check_file_exists "$LIB_DIR/$DYNAMIC_LIB_REALNAME"; then
        prt_info "删除动态库: $LIB_DIR/$DYNAMIC_LIB_REALNAME"
        rm -f "$LIB_DIR/$DYNAMIC_LIB_REALNAME"
        files_removed=$((files_removed + 1))
    else
        prt_warn "动态库不存在: $LIB_DIR/$DYNAMIC_LIB_REALNAME"
    fi
    # 删除符号链接
    if [ -L "$LIB_DIR/$DYNAMIC_LIB_SONAME" ]; then
        prt_info "删除符号链接: $LIB_DIR/$DYNAMIC_LIB_SONAME"
        rm -f "$LIB_DIR/$DYNAMIC_LIB_SONAME"
        files_removed=$((files_removed + 1))
    else
        prt_warn "符号链接不存在: $LIB_DIR/$DYNAMIC_LIB_SONAME"
    fi
    if [ -L "$LIB_DIR/$DYNAMIC_LIB_LINKNAME" ]; then
        prt_info "删除符号链接: $LIB_DIR/$DYNAMIC_LIB_LINKNAME"
        rm -f "$LIB_DIR/$DYNAMIC_LIB_LINKNAME"
        files_removed=$((files_removed + 1))
    else
        prt_warn "符号链接不存在: $LIB_DIR/$DYNAMIC_LIB_LINKNAME"
    fi
    # 更新动态库缓存
    if [ $files_removed -gt 0 ]; then
        prt_info "更新动态库缓存..."
        ldconfig
        prt_dbug "卸载完成，共删除 $files_removed 个文件"
    else
        prt_warn "没有找到需要卸载的文件"
    fi

    prt_info "开始卸载测试程序文件..."
    # 检查文件是否存在并删除
    # 删除测试程序
    if check_file_exists "$TEST_DIR/$TEST_FILE"; then
        prt_info "删除测试程序: $TEST_DIR/$TEST_FILE"
        rm -f "$TEST_DIR/$TEST_FILE"
        files_removed=$((files_removed + 1))
    else
        prt_warn "测试程序不存在: $TEST_DIR/$TEST_FILE"
    fi
}

# 显示状态
show_status() {
    prt_info "库文件状态检查:"
    echo
    local files=(
        "$LIB_DIR/$STATIC_LIB"
        "$LIB_DIR/$DYNAMIC_LIB_REALNAME"
        "$LIB_DIR/$DYNAMIC_LIB_SONAME"
        "$LIB_DIR/$DYNAMIC_LIB_LINKNAME"
    )
    local file_names=(
        "静态库"
        "动态库"
        "SONAME链接"
        "主链接"
    )
    for i in "${!files[@]}"; do
        if [ -e "${files[$i]}" ]; then
            if [ -L "${files[$i]}" ]; then
                echo -e "${GREEN}✓${NC} ${file_names[$i]}: ${files[$i]} -> $(readlink "${files[$i]}")"
            else
                echo -e "${GREEN}✓${NC} ${file_names[$i]}: ${files[$i]}"
            fi
        else
            echo -e "${RED}✗${NC} ${file_names[$i]}: ${files[$i]} (不存在)"
        fi
    done
}

# 显示帮助信息
show_help() {
    echo "库文件管理脚本"
    echo
    echo "用法: $0 [命令]"
    echo
    echo "命令:"
    echo "  install    安装库文件到系统目录"
    echo "  uninstall  从系统目录卸载库文件"
    echo "  status     显示当前安装状态"
    echo "  help       显示此帮助信息"
    echo
    echo "示例:"
    echo "  sudo $0 install    # 安装库文件"
    echo "  sudo $0 uninstall  # 卸载库文件"
    echo "  $0 status          # 查看状态"
    echo
    echo "配置参数:"
    echo "  LIB_DIR: $LIB_DIR"
    echo "  静态库: $STATIC_LIB"
    echo "  动态库: $DYNAMIC_LIB_REALNAME"
    echo "  SONAME: $DYNAMIC_LIB_SONAME"
    echo "  主链接: $DYNAMIC_LIB_LINKNAME"
}

# 主函数
main() {
    case "$1" in
        "install")
            check_permission
            install_libraries
            ;;
        "uninstall")
            check_permission
            uninstall_libraries
            ;;
        "status")
            show_status
            ;;
        "help"|"-h"|"--help")
            show_help
            ;;
        *)
            if [ -z "$1" ]; then
                show_help
            else
                prt_erro "未知命令: $1"
                echo
                show_help
                exit 1
            fi
            ;;
    esac
}

# 脚本入口
if [ "${BASH_SOURCE[0]}" = "$0" ]; then
    main "$@"
fi
